package cn.com.activemq;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

public class JMSPublisher {
	private static final String USERNAME = ActiveMQConnectionFactory.DEFAULT_USER; 
	private static final String PASSWORD = ActiveMQConnectionFactory.DEFAULT_PASSWORD; 
	private static final String BROKERURL = ActiveMQConnectionFactory.DEFAULT_BROKER_URL; 
	
    public static void main( String[] args ) throws JMSException
    {
    	ConnectionFactory connectionFactory; // 消息中间件的连接工厂
    	Connection connection = null; // 消息连接
    	Session session = null; // 创建会话
    	
    	connectionFactory = new ActiveMQConnectionFactory(USERNAME,PASSWORD,BROKERURL);
    	try {
			connection = connectionFactory.createConnection();
			
			// 要先启动链接才能创建会话
			connection.start();
			// 创建session，进行消息的发送
			session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
			
			// 创建topic
			Destination topic = session.createTopic("topic1");
			
			// 创建消息生产者
			MessageProducer messageProducer = session.createProducer(null);
			
			// 模拟发送消息
			for (int i = 0; i < 5; i++) {
				TextMessage textMessage = session.createTextMessage("给订阅者发送的消息：topic"+i);
				messageProducer.send(topic,textMessage,  
	                    DeliveryMode.PERSISTENT, 4, 1000 * 60 * 10);
				try {  
		            Thread.sleep(1000);  
		        } catch(InterruptedException e) {  
		            e.printStackTrace();  
		        }  
			}
			for (int i = 0; i < 5; i++) {
				 MapMessage message = session.createMapMessage();
				 message.setString("name", "张三"+i);
				 message.setInt("age", i);
				 messageProducer.send(topic,message,  
		                    DeliveryMode.PERSISTENT, 4, 1000 * 60 * 10);
				 try {  
			            Thread.sleep(1000);  
			        } catch(InterruptedException e) {  
			            e.printStackTrace();  
			        }  
			}
		} catch (JMSException e) {
			e.printStackTrace();
		} finally {
			if (connection != null) {
				connection.close();
			}
			if (session != null) {
				session.close();
			}
		}
    }
}
